package com.sanjiahantang.youjiaclient.module.me.account.views.impl;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sanjiahantang.plugin.pickerview.OptionsPickerView;
import com.sanjiahantang.uilibrary.popuwindow.SelectPhotoPopupwindow;
import com.sanjiahantang.uilibrary.utils.PickerUtils;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiaclient.R;
import com.sanjiahantang.youjiaclient.base.BaseMvpActivity;
import com.sanjiahantang.youjiaclient.base.BaseView;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.config.SPConfig;
import com.sanjiahantang.youjiaclient.module.common.beans.ConditionBean;
import com.sanjiahantang.youjiaclient.module.common.views.impl.LoveActivity;
import com.sanjiahantang.youjiaclient.module.common.views.impl.SelectorActivity;
import com.sanjiahantang.youjiaclient.module.me.account.presenters.AccountPresenter;
import com.sanjiahantang.youjiaclient.module.me.account.views.AccountView;
import com.sanjiahantang.youjiaclient.utils.CheckUtil;
import com.sanjiahantang.youjiaclient.utils.KeyBoardUtils;
import com.sanjiahantang.youjiaclient.utils.SPUtils;

import java.io.File;
import java.util.ArrayList;

import static com.sanjiahantang.youjiaclient.config.StaticValue.COLOR_PRIMARY;
import static com.sanjiahantang.youjiaclient.config.StaticValue.KEY_PARAM;
import static com.sanjiahantang.youjiaclient.config.StaticValue.KEY_TITLE;
import static com.sanjiahantang.youjiaclient.module.common.views.SelectorView.KEY_INDEX;
import static com.sanjiahantang.youjiaclient.module.decorate.views.DecorateManageView.INTENT_JOB;
import static com.sanjiahantang.youjiaclient.module.decorate.views.DecorateManageView.INTENT_Love;

/**
 * Created by sks on 2015/9/16.
 * 我的资料
 */
public class AccountActivity extends BaseMvpActivity<AccountView, AccountPresenter>
        implements AccountView, View.OnClickListener {
    private Context context;
    private TextView title;
    private ImageView back;
    private View parentView;
    private SelectPhotoPopupwindow photoPopupwindow;
    private OptionsPickerView pvOptions;
    private boolean pickerDataFlag = false;
    private String hobbyKey,hobbyValue;
    private LinearLayout panelHobby;


    private View
            rlGender, //性别
            rlUserName,
            rlJob, //职业
            rlLocation, //所在地
            rlQR; //我的二维码
    private TextView txtPhone, //手机号
            txtGender, //性别
            txtJob, //职业
            txtLocation, //所在地
            txtGHT; //高汇通userId
           // txtInterest; //兴趣
    private EditText txtUserName; //姓名
    private ArrayList<String> listProvince;
    private ArrayList<ArrayList<String>> listCity;
    private ArrayList<ArrayList<ArrayList<String>>> listArea;
    private ConditionBean.SelectorData jobData;

    @Override
    public void initView() {
        setContentView(R.layout.activity_me_accout);
        context = this;

        title = (TextView) findViewById(R.id.title);
        title.setText("我的资料");

        rlGender = findViewById(R.id.rlGender);
        rlJob = findViewById(R.id.rlJob);
        rlLocation = findViewById(R.id.rlLocation);
        rlQR = findViewById(R.id.rlQR);
        rlGender.setOnClickListener(this);
        rlJob.setOnClickListener(this);
        rlLocation.setOnClickListener(this);
        rlQR.setOnClickListener(this);

        panelHobby = (LinearLayout) findViewById(R.id.panelHobby);
        txtPhone = (TextView) findViewById(R.id.txtPhone);
        txtUserName = (EditText) findViewById(R.id.txtUserName);
        txtGender = (TextView) findViewById(R.id.txtGender);
        txtJob = (TextView) findViewById(R.id.txtJob);
        txtLocation = (TextView) findViewById(R.id.txtLocation);
        txtGHT = (TextView) findViewById(R.id.txtGHT);
        findViewById(R.id.panelHobby).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                Intent intent1 = new Intent(context, LoveActivity.class);
                Bundle c = new Bundle();
                c.putSerializable(KEY_PARAM, ConfigValue.favoritelist);
                intent1.putExtra(KEY_PARAM, c);
                intent1.putExtra(KEY_TITLE, "选择爱好");
                intent1.putExtra("isSelect",hobbyValue == null ? new String[]{} : hobbyValue.split(","));
                startActivityForResult(intent1, INTENT_Love);
                return false;
            }
        });
        findViewById(R.id.fl_Left).setOnClickListener(this);
        parentView = findViewById(R.id.lineLayMain);
        photoPopupwindow = new SelectPhotoPopupwindow(context, this);
        txtUserName.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //event.getAction() == KeyEvent.ACTION_UP
                if (keyCode == KeyEvent.KEYCODE_ENTER) {

                    if (TextUtils.isEmpty(txtUserName.getText())){
                        Utils.showToast($this,"请填写昵称");
                        return true;
                    }

                    if (CheckUtil.isEmoji(txtUserName.getText().toString())){
                        Utils.showToast($this,"昵称存在非法字符");
                        return true;
                    }


                    presenter.setData(context, txtUserName.getText().toString(), "", "", txtJob.getText().toString(), txtLocation.getText().toString(), "", "", "name",
                            new BaseView.OnLoadListener() {
                                @Override
                                public void onLoad(Object content) {
                                    SPUtils.put(context, SPConfig.USERNAME,txtUserName.getText());
                                }
                            });
                    KeyBoardUtils.closeKeybord(txtUserName, $this);
                    return true;
                }
                return false;
            }
        });

        presenter.init(context);
        presenter.setOnLoadListener(new OnLoadListener() {
            @Override
            public void loadData(ConditionBean.SelectorData data) {
                if (!TextUtils.isEmpty(data.getDicCode())) {
                    jobData = new ConditionBean.SelectorData();
                    jobData.setDicCode(data.getDicCode());
                    jobData.setDicName(data.getDicName());
                    txtJob.setText(data.getDicName());
                }
            }
        });
        init();
    }

    @Override
    public void initData() {


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rlGender:
                PickerUtils.alertBottomWheelOption(context, presenter.getGenderList(), new PickerUtils.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int position) {
                        setGender(presenter.getGenderList().get(position));
                        presenter.setData(context, txtUserName.getText().toString(), "" + position, "", txtJob.getText().toString(), txtLocation.getText().toString(), "", "", "sex");
                    }
                });
                break;
            case R.id.rlJob://职业
                Intent intent = new Intent(context, SelectorActivity.class);
                Bundle b = new Bundle();
                b.putSerializable(KEY_PARAM, ConfigValue.dutylist);
                intent.putExtra(KEY_PARAM, b);
                intent.putExtra(KEY_TITLE, "选择职业");
                if (jobData != null)
                intent.putExtra(KEY_INDEX,jobData.getDicValue());
                startActivityForResult(intent, INTENT_JOB);
                break;
            case R.id.rlLocation:
                if (pickerDataFlag) {
                    pvOptions.show();
                }
                break;
            case R.id.rlQR:
                presenter.goPageQR(context);
                break;
            case R.id.fl_Left:
                finish();
                break;

        }
    }


    public void init() {
        presenter.loadPersonCityList($this, new BaseView.OnLoadListener() {
            @Override
            public void onLoad(Object content) {
                Object[] listArray = (Object[]) content;
                listProvince = (ArrayList<String>) listArray[0];
                listCity = (ArrayList<ArrayList<String>>) listArray[1];
                listArea = (ArrayList<ArrayList<ArrayList<String>>>) listArray[2];
                pvOptions = new OptionsPickerView.Builder($this, new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        String tx = listProvince.get(options1) + " " +
                                listCity.get(options1).get(options2) + " " +
                                listArea.get(options1).get(options2).get(options3);
                        txtLocation.setText(tx);
                        presenter.setData(context, txtUserName.getText().toString(), "", "", "", txtLocation.getText().toString(), "", "", "address");

                    }
                })

                        .setTitleText("")
                        .setDividerColor(Color.BLACK)
                        .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                        .setContentTextSize(20)
                        .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
           pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
                pvOptions.setPicker(listProvince, listCity, listArea);//三级选择器
                pickerDataFlag = true;
            }
        });
    }

//    public void result(BaseBean model) {
//        if (null != model && model.getCode() > 0) {
//            if (model.getCode() == RESPONSE_CODE_SUC) {
////                ConfigValue.userInfo.setBirthday(birthday);
////                ConfigValue.userInfo.setSex(String.valueOf(sex));
//            }
//            Utils.showToast(context, model.getMessage());
//        } else
//            Utils.showToast(context, "提交失败");
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        File file = new File("/sdcard/head.jpg");
        if (file.exists())
            file.delete();

    }

    @Override
    public AccountPresenter initPresenter() {
        return new AccountPresenter();
    }


    @Override
    public void showProgress() {
        super.showProgress(context);
    }

    @Override
    public void setName(String name) {
        txtUserName.setText(name);
        txtUserName.setSelection(txtUserName.getText().toString().length());
        if (ConfigValue.userInfo != null){
            ConfigValue.userInfo.setUserName(name);
        }
    }

    @Override
    public void setGender(String gender) {
        txtGender.setText(gender);
    }

    @Override
    public void setPhone(String phone) {
        txtPhone.setText(phone);

    }

    @Override
    public void setJob(ConditionBean.SelectorData data) {
        jobData = data;
        if (data == null){
            txtJob.setText("未设置");
        }else{
            txtJob.setText(data.getDicName());
        }

    }

    @Override
    public void setLocate(String locate) {
        txtLocation.setText(locate);
        ConfigValue.userInfo.setAddress(locate);
    }

    @Override
    public void setHobby(String hobbyCode,String hobbyName) {
        int d5 = Utils.dip2px(context,5);
        if (!TextUtils.isEmpty(hobbyCode)&&!TextUtils.isEmpty(hobbyName)){
            String [] hobby = hobbyName.split(",");
            hobbyKey = hobbyCode;
            hobbyValue = hobbyName;
            panelHobby.removeAllViews();
            for (int i = 0;i < hobby.length;i++){
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

                TextView textView = new TextView(context);
                textView.setBackgroundResource(R.drawable.x_shape_green_border);
                textView.setTextColor(COLOR_PRIMARY);
                textView.setTextSize(12);

                params.setMargins(d5,0,d5,0);
                textView.setPadding(d5 * 2,d5,d5 * 2,d5);
                textView.setText(hobby[i]);
                textView.setLayoutParams(params);
                panelHobby.addView(textView);
            }
        }else{
            panelHobby.removeAllViews();
            TextView textView = new TextView(context);
            textView.setTextColor(Color.rgb(0x90,0x90,0x90));
            textView.setTextSize(14);
            textView.setPadding(0,0,0,d5);
            textView.setText("未设置");
            panelHobby.addView(textView);
        }

    }

    @Override
    public void setGHTUserId(String ghtUserId) {
        txtGHT.setText(ghtUserId);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != Activity.RESULT_OK) {
            switch (requestCode) {
                case INTENT_JOB:
                    if (data != null) {
                        jobData = (ConditionBean.SelectorData) data.getSerializableExtra(KEY_PARAM);
                        if (jobData != null) {
                            txtJob.setText(jobData.getDicName());
                            presenter.setData(context, txtUserName.getText().toString(), "", jobData.getDicCode(), txtJob.getText().toString(), txtLocation.getText().toString(), "", "", "job");
                        }
                    }
                    break;
                case INTENT_Love:
                    if (data != null) {
                        String value = data.getStringExtra("favoriteValue");
                        String key = data.getStringExtra("favoriteKey");
                        setHobby(key,value);
                        presenter.setData(context, "", "", "", "", "", key, value, "like");
                    }
                    break;
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onBackPressed() {
        if (pvOptions != null && pvOptions.isShowing()) {
            pvOptions.dismiss();
            return;
        }
        super.onBackPressed();
    }
}
